
cmake_minimum_required(VERSION 3.10)
project(ip_reassembly LANGUAGES C)

# 查找 pkg-config
find_package(PkgConfig REQUIRED)

# 检查 DPDK 是否存在
execute_process(
    COMMAND ${PKG_CONFIG_EXECUTABLE} --exists libdpdk
    RESULT_VARIABLE DPDK_FOUND
)
if(NOT DPDK_FOUND EQUAL 0)
    message(FATAL_ERROR "no installation of DPDK found")
endif()

# 获取 DPDK 的编译选项
execute_process(
    COMMAND ${PKG_CONFIG_EXECUTABLE} --cflags libdpdk
    OUTPUT_VARIABLE DPDK_CFLAGS
    OUTPUT_STRIP_TRAILING_WHITESPACE
)
separate_arguments(DPDK_CFLAGS UNIX_COMMAND "${DPDK_CFLAGS}")

# 获取共享库链接参数
execute_process(
    COMMAND ${PKG_CONFIG_EXECUTABLE} --libs libdpdk
    OUTPUT_VARIABLE DPDK_SHARED_LIBS
    OUTPUT_STRIP_TRAILING_WHITESPACE
)
separate_arguments(DPDK_SHARED_LIBS UNIX_COMMAND "${DPDK_SHARED_LIBS}")

# 获取静态库链接参数并检查格式（模拟原Makefile的检查）
execute_process(
    COMMAND ${PKG_CONFIG_EXECUTABLE} --static --libs libdpdk
    OUTPUT_VARIABLE DPDK_STATIC_LIBS
    OUTPUT_STRIP_TRAILING_WHITESPACE
)
separate_arguments(DPDK_STATIC_LIBS UNIX_COMMAND "${DPDK_STATIC_LIBS}")

string(REGEX MATCH "whole-archive.*l:lib.*no-whole-archive" DPDK_STATIC_CHECK "${DPDK_STATIC_LIBS}")
if(NOT DPDK_STATIC_CHECK)
    message(FATAL_ERROR "Cannot generate statically-linked binaries: Invalid static library flags")
endif()

# 添加编译选项
add_compile_options(-O3 ${DPDK_CFLAGS} -DALLOW_EXPERIMENTAL_API)

# 创建可执行文件
add_executable(ip_reassembly-shared main.c)
add_executable(ip_reassembly-static main.c)

# 链接库
target_link_libraries(ip_reassembly-shared PRIVATE ${DPDK_SHARED_LIBS})
target_link_libraries(ip_reassembly-static PRIVATE ${DPDK_STATIC_LIBS})

# 创建符号链接的自定义目标
add_custom_target(shared
    DEPENDS ip_reassembly-shared
    COMMAND ${CMAKE_COMMAND} -E remove -f ip_reassembly
    COMMAND ${CMAKE_COMMAND} -E create_symlink ip_reassembly-shared ip_reassembly
    WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
)

add_custom_target(static
    DEPENDS ip_reassembly-static
    COMMAND ${CMAKE_COMMAND} -E remove -f ip_reassembly
    COMMAND ${CMAKE_COMMAND} -E create_symlink ip_reassembly-static ip_reassembly
    WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
)
